

import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';

class StringUtil{
  static bool isEmpty(String msg){
    return msg == null || msg.isEmpty;
  }

  static String replace(String source, String replacement, int startIndex, int endIndex){
    if (StringUtil.isEmpty(source)){
      return source;
    }
    return source.replaceRange(startIndex, endIndex, replacement);
  }

  static double moneyString2double(String source){
    double result = 0;
    if(!StringUtil.isEmpty(source)){
      result = double.parse(source.replaceAll(",", ""));
    }
    return result;
  }

  /// 转小数
  /// @param number 原数
  /// @param decimalPlace 小数位数
  /// @return
  static String number2DecimalFormat(double number, int fractionDigits){
    return number.toStringAsFixed(fractionDigits);
  }

  static String doubleNumber2String({@required double num, int fractionDigits = 2}){
    //billion 十亿，million 百万
    if(num > 999) {
      double result;
      String unit = "";
      if (num > 99999999) { //亿
        result = num / 1000000000;
        unit = "b";
      } else if (num > 999999) { //百万
        result = num / 1000000;
        unit = "m";
      } else if (num > 999) { //千
        result = num / 1000;
        unit = "k";
      }
      return result.toStringAsFixed(fractionDigits) + unit;
    } else {
      return "$num";
    }
  }

  static String intNumber2String({@required int num, int fractionDigits = 2}){
    //billion 十亿，million 百万
    if(num > 999) {
      double result;
      String unit = "";
      if (num > 99999999) { //亿
        result = num / 1000000000.0;
        unit = "b";
      } else if (num > 999999) { //百万
        result = num / 1000000.0;
        unit = "m";
      } else if (num > 999) { //千
        result = num / 1000.0;
        unit = "k";
      }
      return result.toStringAsFixed(fractionDigits) + unit;
    } else {
      return "$num";
    }
  }


  // 去掉文本中的html代码
  static RegExp regExp1 = RegExp("</.*>");
  static RegExp regExp2 = RegExp("<.*>");
  static String clearHtmlContent(String str) {
    if (str.startsWith("<emoji")) {
      return "[emoji]";
    }
    var s = str.replaceAll(regExp1, "");
    s = s.replaceAll(regExp2, "");
    s = s.replaceAll("\n", "");
    return s;
  }

  static String createHtml(String body){
    body = """<html>
                    <head>
                      <meta charset="utf-8">
                      <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
                      <meta name="apple-mobile-web-app-capable" content="yes">
                    </head>
                    <body>
                      $body
                    </body>
                  </html>
                  """;
    return body;
  }

  static String getEncodePassword(String password){
    var bytes = utf8.encode(password); // data being hashed
    String digest = sha1.convert(bytes).toString();
    return digest;
  }
}